
#include <tbb/atomic.h>
#include <tbb/mutex.h>
#include <iostream>

template<class T,class Mutex=tbb::mutex>  
class lazy {  
        tbb::atomic<T*> value;  
        Mutex mu;
        bool killed;
public:  
        lazy() : value(),killed(false){}  
        ~lazy(){ if(value) delete value; }  
  
        T* get(){  
                if( !value ){  
                        typename Mutex::scoped_lock lock(mu);
                        if(!value && !killed)
                                 value = new T();
                }  
                return value;  
        } 

        void destroy(){
                killed = true;
                delete value;
                value = 0;
        }
};  

struct A{
        void hello(){
                std::cout << "Hello!\n";
        }
};

lazy<A> gl_a;
A* get_a(){
        return gl_a.get();
}
void destroy_a(){
        gl_a.destroy();
}


int main(){
        A* tmp = get_a();
        if(tmp) tmp->hello();
       
        destroy_a();
 
        tmp = get_a();
        if(tmp) tmp->hello();
}
